<template>
  <n-card :bordered="false">
    <n-alert type="warning" class="alert_small m-b-10">
      温馨提示：可设定vip各项参数
      &nbsp;
      如：类型、价格、状态等
    </n-alert>
    <n-alert :show-icon="false" class="m-b-10">
      <n-form :model="search_param" class="search-forms"
              inline
              :show-feedback="false"
              label-placement="left"
              @keydown.enter.prevent="handleSubmitSearch">
        <n-form-item label="名称">
          <n-input v-model:value="search_param.key" placeholder="请输入名称查询" style="width:230px"
                   clearable/>
        </n-form-item>
        <n-form-item label="状态">
          <n-select v-model:value="search_param.status" :options="statusOption" style="width: 130px;" clearable/>
        </n-form-item>
        <n-form-item>
          <search-button-group @submit="handleSubmitSearch"
                               @reset="()=>(search_param.key=null,search_param.status=null)"/>
        </n-form-item>
      </n-form>
    </n-alert>
    <data-table ref="data_list"
                :columns="columns"
                :action-column="actionColumn"
                :row-key="(row:Recordable) => row.id"
                :params="search_param"
                list-url="vip/list"
                default-serial-number
                serial-number-title="序号">
      <template #toolbarLeft>
        <n-button type="success" v-permission="['vip:add']" @click="()=>(addEditModel=true)">
          <n-icon :size="18">
            <AddSharp/>
          </n-icon>
          新增
        </n-button>
      </template>
    </data-table>
    <!--新增、修改vip-->
    <n-modal v-model:show="addEditModel"
             :title="addEditForm.id?'修改vip':'新增vip'" :mask-closable="false"
             :show-icon="false" preset="dialog" style="width: 810px" @after-leave="closeAddEditModel">
      <n-form ref="addEditFormRef" :model="addEditForm" :rules="addEditFormRules" require-mark-placement="left"
              label-width="auto" label-placement="left">
        <n-form-item label="名称" path="name">
          <n-input v-model:value="addEditForm.name" placeholder="请填写名称" clearable/>
        </n-form-item>
        <n-form-item label="图片" path="banner">
         <image-selection v-model:value="addEditForm.banner"/>
        </n-form-item>
        <n-form-item label="VIP广告位" path="isUc">
          <div>
            <n-radio-group v-model:value="addEditForm.isUc" name="isUcVip">
              <n-space>
                <n-radio :value="0" :key="0" label="不显示"/>
                <n-radio :value="1" :key="1" label="显示"/>
              </n-space>
            </n-radio-group>
            <p class="tips_p">指的是用户中心中的vip广告位</p>
          </div>
        </n-form-item>
        <n-form-item label="字体颜色" path="tColor" v-if="addEditForm.isUc">
          <n-color-picker v-model:value="addEditForm.tColor" style="width: 100px;" :modes="['hex']"
                          :actions="['clear']"/>
        </n-form-item>
        <n-form-item label="VIP权限" path="dType">
          <n-checkbox-group v-model:value="addEditForm.dType">
            <n-space item-style="display: flex;">
              <template v-for="item in vipTypeOptions">
                <n-checkbox :value="item.value" :label="item.label"/>
              </template>
            </n-space>
          </n-checkbox-group>
        </n-form-item>
        <n-form-item label="VIP类型" path="type">
          <n-radio-group v-model:value="addEditForm.type" name="type">
            <n-space>
              <n-radio :value="0" :key="0" label="永久"/>
              <n-radio :value="1" :key="1" label="包年"/>
              <n-radio :value="2" :key="2" label="包月"/>
              <n-radio :value="3" :key="3" label="包半个月"/>
            </n-space>
          </n-radio-group>
        </n-form-item>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="原价" path="price">
            <div>
              <n-input-group>
                <n-input-number v-model:value="addEditForm.price" :min="0" :precision="2" :show-button="false"
                                clearable/>
                <n-input-group-label>元</n-input-group-label>
              </n-input-group>
              <p class="tips_p">用户购买vip价格</p>
            </div>
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="优惠价" path="disPrice">
            <div>
              <n-input-group>
                <n-input-number v-model:value="addEditForm.disPrice" :min="0" :precision="2" :show-button="false"
                                clearable/>
                <n-input-group-label>元</n-input-group-label>
              </n-input-group>
              <p class="tips_p">用户购买vip优惠价格</p>
            </div>
          </n-form-item-gi>
        </n-grid>

        <!--        <n-form-item label="折扣" path="discount">-->
        <!--          <div>-->
        <!--            <n-input-group>-->
        <!--              <n-input-number v-model:value="addEditForm.discount" :min="0" :max="10" :precision="2"-->
        <!--                              :show-button="false"-->
        <!--                              placeholder="vip折扣 如：1.5折" clearable/>-->
        <!--              <n-input-group-label>折</n-input-group-label>-->
        <!--            </n-input-group>-->
        <!--            <p class="tips_p">折扣课程折扣以按折算、最大值10，如：5折 </p>-->
        <!--          </div>-->
        <!--        </n-form-item>-->

                <n-form-item label="指定折扣课程" path="cId" v-if="dTypeCourseMet">
                  <div>
                    <n-button type="primary" size="small" @click="()=>(selectCourse=true)">选择课程</n-button>
                    <div v-if="addEditForm.cId" class="m-t-5">
                      <n-checkbox-group v-model:value="addEditForm.cId">
                        <template v-for="item in addEditForm.cId">
                          <n-checkbox :value="item" :label="getSourceName(item)"/>
                        </template>
                      </n-checkbox-group>
                    </div>
                  </div>
                </n-form-item>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="状态" path="status">
            <n-switch :round="false" v-model:value="addEditForm.status" :checked-value="1" :unchecked-value="0">
              <template #checked>
                正常
              </template>
              <template #unchecked>
                停用
              </template>
            </n-switch>
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="排序" path="sort">
            <n-input-number v-model:value="addEditForm.sort" :show-button="false" clearable/>
          </n-form-item-gi>
        </n-grid>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="()=>(addEditModel=false)">取消</n-button>
          <n-button type="primary" :loading="handelSubmitLoading" @click="handelSubmitData">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
  <!--选择课程-->
  <n-modal v-model:show="selectCourse" title="选择课程" :mask-closable="false"
           :show-icon="false" preset="dialog" style="width: 610px">
    <n-form :model="search_source" class="search-forms"
            inline
            :show-feedback="false"
            label-placement="left"
            @keydown.enter.prevent="handleSubmitSearchSource">
      <n-form-item>
        <n-input v-model:value="search_source.key" placeholder="请输入课程名称查询" style="width:260px"
                 clearable/>
      </n-form-item>
      <n-form-item>
        <n-button type="primary" @click="handleSubmitSearchSource">
          <template #icon>
            <n-icon>
              <IosSearch/>
            </n-icon>
          </template>
          查询
        </n-button>
      </n-form-item>
    </n-form>
    <n-data-table class="m-t-10"
                  size="small"
                  :columns="selectCourseColumn"
                  :row-key="(row:Recordable) => row.id"
                  :data="selectCourseDate"
                  :pagination="false" :max-height="350" @update:checked-row-keys="selectedCourse">
      <template #empty>
        <n-empty description="暂无相关数据">
          <template #icon>
            <n-icon size="42">
              <BoxOpen/>
            </n-icon>
          </template>
        </n-empty>
      </template>
    </n-data-table>
  </n-modal>
</template>
<script setup lang="ts">
import {h, ref, reactive, onMounted, computed} from 'vue'
import SearchButtonGroup from '@components/SearchButtonGroup';
import {NImage, NPopconfirm, NTag, SelectOption, useMessage, FormInst, FormItemRule} from "naive-ui";


import DataTable from '@components/DataTable'
import DataTableAction from '@components/DataTable/src/components/DataTableAction';
import {AddSharp} from "@vicons/material";
import {delRequest, postPutRequest, getRequest} from "@/api/data.ts";


import {IosSearch} from "@vicons/ionicons4";
import {BoxOpen} from "@vicons/fa";

import ImageSelection from "@components/ImageSelection";
import {imagePreview} from '@/util';

const message = useMessage()


const statusOption = ref<SelectOption[]>([
  {
    label: '启用',
    value: 1,
  }, {
    label: '停用',
    value: 0,
  }
])

const search_param = ref({
  key: null,
  status: null,
})
const vipTypeOptions = ref([
  {
    label: '所有资料',
    value: 1,
  }, {
    label: '所有课程',
    value: 2,
  }, {
    label: '指定课程',
    value: 3,
  }, {
    label: '指定课程资料',
    value: 4,
  }, {
    label: '可更换教师',
    value: 5,
  }
])
//数据表
const data_list = ref<any>();
const columns = ref([
  {
    title: '名称',
    key: 'name',
  }, {
    title: '图片',
    key: 'banner',
    width: 100,
    align: 'center',
    render(row: { banner: string }) {
      if (row.banner) {
        return h(NImage, {
          width: 20,
          height: 20,
          src: imagePreview(row.banner)
        })
      }
    }
  }, {
    title: '价格(元)',
    key: 'price',
    width: 100,
    align: 'center',
    render(row: { price: number }) {
      return h('span', null, {default: () => (row.price?.toFixed(2))});
    }
  }, {
    title: '优惠价(元)',
    key: 'disPrice',
    width: 100,
    align: 'center',
    render(row: { disPrice: number }) {
      return h('span', null, {default: () => (row.disPrice?.toFixed(2))});
    }
  },
  {
    title: 'vip权限',
    key: 'dtype',
    width: 300,
    render(row: { dtype: number[]|string[] }) {
      let text='';
      if (row.dtype.length>=1){
        text=getLabelsByValues(row.dtype).join('、');
      }
      return h('span', null, {default: () => (text)});
    }
  }, {
    title: 'vip类型',
    key: 'type',
    width: 100,
    align: 'center',
    render(row: { type: number }) {
      let type_text = '';
      switch (row.type) {
        case 0:
          type_text = '永久';
          break;
        case 1:
          type_text = '包年';
          break;
        case 2:
          type_text = '包月';
          break;
        case 3:
          type_text = '包半个月';
          break;
      }
      return h('span', null, {default: () => (type_text)});
    }
  },
  {
    title: '状态',
    key: 'status',
    width: 80,
    align: 'center',
    render(row: { status: boolean | number }) {
      const enabled_color = row.status ? 'success' : 'warning';
      const enabled_text = row.status ? '正常' : '停用';
      return h(NTag,
          {
            type: enabled_color,
          },
          {
            default: () => (enabled_text),
          }
      );
    }
  }, {
    title: '创建时间',
    key: 'createTime',
    width: 175,
  }, {
    title: '更新时间',
    key: 'updateTime',
    width: 175,
  },
])
//操作列
const actionColumn = reactive({
  width: 120,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    return h(DataTableAction, {
      actions: [
        {
          label: '修改',
          onClick: handleEdit.bind(null, record),
          type: 'primary',
          permission: ['vip:edit']
        },
        {
          label: '删除',
          type: 'error',
          popConfirm: NPopconfirm,
          onPositiveClick: handleDelete.bind(null, record),
          confirm: {
            text: '确定删除当前vip吗？',
          },
          permission: ['vip:del']
        },
      ]
    });
  },
});
//新增、修改vip
const addEditModel = ref<boolean>(false);
const addEditFormRef = ref<FormInst | null>(null);
const handelSubmitLoading = ref<boolean>(false);
const selectCourse = ref<boolean>(false);//选择课程模态框
const addEditForm = ref({
  id: 0,
  name: '',
  banner: null,
  dType:<number[]> [],
  type: 0,
  price: null,
  disPrice: null,
  isUc: 0,
  tColor: null,
  cId: <Array<string | number>>[],
  discount: null,
  status: 1,
  sort:100
})
const addEditFormRules = computed(() => {
  return {
    name: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写名称'
    },
    banner: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请选择图片'
    },
    dType: {
      type: 'array',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择VIP权限'
    },
    type: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择vip类型'
    },
    price: {
      type: 'number',
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写原价'
    },
    discount: {
      type: 'number',
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写折扣'
    },
    cId: {
      type: 'array',
      required: true,
      trigger: ['blur', 'input'],
      message: '请选择课程'
    },
    tColor: {
      required: !!addEditForm.value.isUc,
      trigger: ['blur', 'change'],
      message: '请选择字体颜色'
    },
    disPrice:{
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      // message: '请填写优惠价',
      validator: (_rule: FormItemRule, value: number) => {
        return new Promise<void>((resolve, reject) => {
          console.log(value)
          if (!value) {
            reject(Error('请填写优惠价'))
          } else if (addEditForm.value.price && addEditForm.value.price<value) {
            reject(Error('优惠价不得大于原价')) // reject with error message
          } else {
            resolve()
          }
        })
      }
    }
  }
})

const search_source = ref({
  key: null
})
const selectCourseColumn = ref([
  {
    type: 'selection',
  },
  {
    title: '课程名称',
    key: 'name',
  }, {
    title: '分类',
    key: 'classifyName'
  }, {
    title: '分类',
    key: 'gradeName'
  }
]);
const selectCourseDate = ref([])
const dTypeCourseMet=computed(()=>{
  return  addEditForm.value.dType.includes(3) || addEditForm.value.dType.includes(4);
})

//选中课程
const selectedCourse = (keys: Array<string | number>) => {
  addEditForm.value.cId = keys;
}
//查询
const handleSubmitSearch = () => {
  data_list.value.searchListData();
}
const getLabelsByValues= (values: number[]|string[]): string[] => {
    const labels: string[] = [];
    values.forEach((val) => {
      const item = vipTypeOptions.value.find((d) => d.value === val);
      if (item) {
        labels.push(item.label);
      }
    });
    return labels;

}
//修改
const handleEdit = (record: Recordable) => {
  addEditForm.value.id = record.id;
  addEditForm.value.name = record.name;
  addEditForm.value.status = record.status;
  addEditForm.value.banner = record.banner;
  addEditForm.value.price = record.price;
  addEditForm.value.cId = record.cid && record.cid.length ? record.cid : [];
  addEditForm.value.discount = record.discount;
  addEditForm.value.dType = record.dtype;
  addEditForm.value.type = record.type;
  addEditForm.value.disPrice = record.disPrice;
  addEditForm.value.tColor = record.tColor;
  addEditForm.value.isUc = record.isUc;
  addEditForm.value.sort = record.sort;
  addEditModel.value = true;
}
//删除
const handleDelete = (record: Recordable) => {
  delRequest('vip/del', record.id).then((result: ResponseResult) => {
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          data_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}
const closeAddEditModel = () => {
  addEditForm.value.id = 0;
  addEditForm.value.name = '';
  addEditForm.value.status = 1;
  addEditForm.value.banner = null;
  addEditForm.value.price = null;
  addEditForm.value.cId = [];
  addEditForm.value.discount = null;
  addEditForm.value.dType = [];
  addEditForm.value.type = 0;
  addEditForm.value.disPrice = null;
  addEditForm.value.tColor = null;
  addEditForm.value.isUc = 1;
  addEditForm.value.sort = 100;
  handelSubmitLoading.value = false;
}
//提交新增、修改数据
const handelSubmitData = (e: MouseEvent) => {
  e.preventDefault();
  addEditFormRef.value?.validate((errors) => {
    if (!errors) {
      handelSubmitLoading.value = true;
      const url = addEditForm.value.id ? 'vip/edit' : 'vip/add';
      postPutRequest(url, addEditForm.value, addEditForm.value.id ? 'PUT' : 'POST').then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              addEditModel.value = false;
              if (addEditForm.value.id) {
                data_list.value.reload();
              } else {
                data_list.value.searchListData();
              }
            }
          })
        } else {
          message.error(result.message);
          handelSubmitLoading.value = false;
        }
      })
    }
  })
}
const handleSubmitSearchSource = async () => {
  await getRequest("course/for_vip", {key: search_source.value.key}).then((result: ResponseResult) => {
    const {data} = result;
    selectCourseDate.value = data;
  })
}
const getSourceName = (id: number | string) => {
  const foundObject: any = selectCourseDate.value.find((obj: any) => obj.id === id);
  return foundObject.name;
}
onMounted(() => {
  handleSubmitSearchSource();
})
</script>

<style scoped lang="scss">

</style>